package com.wiz.weixin.controllor;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.MimeTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wiz.weixin.common.ResponseCode;
import com.wiz.weixin.manager.TencentManager;
import com.wiz.weixin.manager.WxUserManager;
import com.wiz.weixin.service.MemberService;
import com.wiz.weixin.service.StationService;
import com.wiz.weixin.service.VerificationCodeService;
import com.wiz.weixin.tencent.vo.UserInfoVo;
import com.wiz.weixin.to.StationTO;
import com.wiz.weixin.util.PastUtil;
import com.wiz.weixin.vo.MemberVO;
import com.wiz.weixin.vo.ResultVO;

/**
 * 会员
 * @author xxy
 */
@Controller
@RequestMapping("/member")
public class MemberControllor {
	private transient final Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	private MemberService memberService;
	@Resource
	private WxUserManager commonManager;
	@Resource
	private TencentManager tencentManager;
	@Resource
	private VerificationCodeService verificationCodeService;
	@Resource
	private StationService stationService;

	/** 中转到注册页面 
	 * @throws Exception */
	@RequestMapping(value = "/toRegister")
	public String toRegister(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "stationId", required = true) String stationId, // 站点id
			@RequestParam(value = "openId", required = true) String openId, // 站点id
			HttpSession session, Model model) throws Exception {
//		openId = "ovNRGs45WudglvjfjUth3W57tJOU";
		String code = request.getParameter("code");
		if(StringUtils.isNotBlank(code)){
			String sessionOpenId = tencentManager.getOpenId(code);
			if(!sessionOpenId.equals(openId)){
				model.addAttribute("msg", "请通过正确二维码或分享链接注册");
				return "/error";
			}
		}
		if (StringUtils.isBlank(openId)) {
			model.addAttribute("msg", "验证失败，请重新扫码");
			return "/member/erro";
		}
		session.setAttribute("openid", openId);
		StationTO to = stationService.getStationById(stationId);
		if(to == null){
			model.addAttribute("msg", "油站不存在，请联系管理员");
			return "/error";
		}
		String hqId = stationService.getHQId(openId,to.getHqId());
		if(StringUtils.isNotBlank(hqId)){
			model.addAttribute("msg", "您已经是会员，无需再次注册");
			return "/error";
		}
		request.setAttribute("stationId", stationId);
		request.setAttribute("hqName", to.getHqName());
		return "/member/register";

	}

	/** 生成验证码 
	 * @throws Exception */
	@RequestMapping(value = "/generateCode")
	@ResponseBody
	public String generateCode(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "phoneNum", required = true) String phoneNum, // 手机号码
			@RequestParam(value = "stationId", required = true) String stationId, // 站点id
			@RequestParam(value = "hqName", required = true) String hqName, // 站点id
			HttpSession session, Model model) throws Exception {
		Pattern p = Pattern.compile("1[0-9]{10}$");
		Matcher m = p.matcher(phoneNum);
		if (!m.matches()) {
			return "{\"code\":999, \"msg\" : \"非法手机号\"}";
		}
		return verificationCodeService.sendCode(phoneNum, stationId, hqName);
	}
	
	/** 生成手机条码 */
	@RequestMapping(value = "/barCode")
	public void getBarcode(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "phoneNum", required = true) String phoneNum, // 手机号码
			HttpSession session, Model model) {
		String format = MimeTypes.MIME_JPEG;// MimeTypes.MIME_JPEG  
		ByteArrayOutputStream bout = null;
		try {
			BarcodeUtil util = BarcodeUtil.getInstance();
			Configuration cfg = buildCfg();
			BarcodeGenerator gen = util.createBarcodeGenerator(cfg);
			bout = new ByteArrayOutputStream(4096);//二进制流
			int dpi = 300; // 分辨率
			int orientation = 0;
			BitmapCanvasProvider bitmap = new BitmapCanvasProvider(bout, format, dpi, BufferedImage.TYPE_BYTE_BINARY,
					false, orientation);
			gen.generateBarcode(bitmap, phoneNum);
			bitmap.finish();
			/*File file = new File("c://" + text + ".jpg");
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bout.toByteArray(), 0, bout.size());*/
			
			 response.setContentType(format);
			 response.setContentLength(bout.size());
			 response.getOutputStream().write(bout.toByteArray());
			 response.getOutputStream().write(bout.toByteArray());
			 response.getOutputStream().flush();

		} catch (Exception e) {
			log.error("Error while generating barcode", e);

		} finally {
			if (bout != null) {
				try {
					bout.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	/** 
	 * 注册会员 
	 * @throws Exception 
	 **/
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "stationId", required = true) String stationId, // 站点id
			@RequestParam(value = "name", required = true) String name, // 会员名称
			@RequestParam(value = "phoneNum", required = true) String phoneNum, // 手机号码
			@RequestParam(value = "authCode", required = true) int authCode, // 验证码
			@RequestParam(value = "idCard", required = false) String idCard, // 身份证
			@RequestParam(value = "licensePlatePut", required = false) String licensePlate, // 车牌
			@RequestParam(value = "fuellingPassword", required = false) String fuellingPw, // 加油密码
			HttpSession session, Model model) throws Exception {
		String openId = (String) session.getAttribute("openid");
		MemberVO member = new MemberVO(null, name, stationId, fuellingPw, licensePlate, idCard, phoneNum, openId);
		String agent = request.getHeader("User-Agent").toLowerCase();
		if (!agent.contains("micromessenger")) {
			model.addAttribute("msg", "请使用微信自带的浏览注册！");
			return "/error";
		}
		if (openId == null || openId.equals("")) {
			model.addAttribute("msg", "不能得到你的微信编码！");
			return "/error";
		}
		PastUtil.setJsSdkInModel(model);
		StationTO stationTO = stationService.getStationById(stationId);
		if(stationTO == null){
			model.addAttribute("msg", "没有找到当前站点");
			return "/error";
		}
		ResultVO result = memberService.register(member,authCode,stationTO);
		if(result.getCode() != 0){
			model.addAttribute("msg", result.getMsg());
			return "/error";
    	}
		UserInfoVo userInfoVo = commonManager.getUserInfo(openId);
		model.addAttribute("userInfo", userInfoVo);
		model.addAttribute("member", member);
		model.addAttribute("hqName", stationTO.getHqName());
		model.addAttribute("hqId", stationTO.getHqId());
		model.addAttribute("stationId", stationTO.getStationId());
		return "/member/success";
	}

	/** 账户余额列表 
	 * @throws Exception */
	@RequestMapping(value = "/listAccount")
	public String listAccount(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			Model model) throws Exception {
		String openId = (String) session.getAttribute("openid");
//		String openId = "ovNRGs45WudglvjfjUth3W57tJOU";
		if (StringUtils.isBlank(openId)) {
			String code = request.getParameter("code");
			openId = tencentManager.getOpenId(code);
			session.setAttribute("openid", openId);
		}
		if(StringUtils.isBlank(openId)){
			model.addAttribute("msg", "未找到微信关联用户");
			return "/error";
		}
		List<String> hqIds = stationService.getHQIds(openId);
		if(hqIds == null || hqIds.size()<= 0){
			model.addAttribute("msg", "对不起，您还未注册，请扫描加油站的二维码进行注册");
			return "/error";
		}
		List<MemberVO> list = memberService.listMemberByOpenId(openId);
		if(list == null || list.size()<= 0){
			model.addAttribute("msg", "对不起，您还未注册，请扫描加油站的二维码进行注册");
			return "/error";
		}
		model.addAttribute("list", list);
		return "/member/listAccount";

	}

	/**
	 * 跳转会员收支明细
	 */
	@RequestMapping(value = "/toDetail", method = RequestMethod.POST)
	public String toDetail(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId, // 总部id
			@RequestParam(value = "memberId", required = true) String memberId, // 站点id
			@RequestParam(value = "hqName", required = true) String hqName, //
			HttpSession session, Model model) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		model.addAttribute("hqId", hqId);
		model.addAttribute("memberId", memberId);
		model.addAttribute("hqName", hqName);
		return "/member/detail";

	}

	/***
	 * 会员收支明细列表
	 */
	@RequestMapping(value = "/details", method = RequestMethod.POST)
	@ResponseBody
	public String details(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId, // 总部id
			@RequestParam(value = "memberId", required = true) String memberId, // 站点id
			@RequestParam(value = "pageNo", required = false, defaultValue = "1") int pageNo, // 当前页
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize, // 每页显示几条记录
			HttpSession session, Model model) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		try {
			return memberService.listAmountHistory(hqId, memberId, pageNo, pageSize);// "10005","10005114317863"
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseCode.PAGE_CODE_ERROR;

	}
	
	@RequestMapping(value = "/bind")
	public String bindOpenId(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "memberId", required = true) String memberId, // 会员id
			@RequestParam(value = "time", required = true) long time, // 时间
			HttpSession session, Model model) throws Exception {
		String agent = request.getHeader("User-Agent").toLowerCase();
		if (!agent.contains("micromessenger")) {
			model.addAttribute("msg", "请使用微信自带的浏览注册！");
			return "/error";
		}
		if(System.currentTimeMillis() - time > 5*60*1000){
			model.addAttribute("msg", "二维码过期");
			return "/error";
		}
		String code = request.getParameter("code");
		String openId = tencentManager.getOpenId(code);
		if (openId == null || openId.equals("")) {
			model.addAttribute("msg", "不能得到你的微信编码！");
			return "/error";
		}
		session.setAttribute("openid", openId);
		int result = memberService.bindOpenId(memberId, openId);
		if(result > 0){
			model.addAttribute("msg", "绑定成功");
			return "/success";
		}else if(result == -1){
			model.addAttribute("msg", "该账号已绑定");
			return "/error";
		}else{
			model.addAttribute("msg", "绑定失败");
			return "/error";
		}
	}
	
	/** 
     * Build an Avalon Configuration object from the request. 
     *  
     * @return the newly built COnfiguration object 
     * @todo Change to bean API 
     */  
    protected Configuration buildCfg()  
    {  
        DefaultConfiguration cfg = new DefaultConfiguration("barcode");  
        // Get type  
        String type = "code128";  
        DefaultConfiguration child = new DefaultConfiguration(type);  
        cfg.addChild(child);  
        return cfg;  
    }  

}
